package com.deliveryservicesystem.presentation.desktop.addpanel;

import com.deliveryservicesystem.app.exceptions.OutputError;
import com.deliveryservicesystem.app.exceptions.PreexistingEntityException;
import com.deliveryservicesystem.app.factory.AppFactory;
import com.deliveryservicesystem.app.util.AppUtils;
import com.deliveryservicesystem.app.validation.SupplierValidator;
import com.deliveryservicesystem.app.validation.ValidationUtil;
import com.deliveryservicesystem.model.Supplier;
import com.deliveryservicesystem.presentation.desktop.InfoLableChangeHandler;
import com.deliveryservicesystem.service.crud.impl.SupplierCrudServiceImpl;
import com.jgoodies.validation.ValidationResult;
import com.jgoodies.validation.view.ValidationComponentUtils;
import com.jgoodies.validation.view.ValidationResultViewFactory;
import java.awt.KeyboardFocusManager;
import java.util.HashMap;
import javax.swing.JOptionPane;

/**
 * File Name: AddEditSupplierPanel.java
 * Version:
 * Description:
 * Package: com.deliveryservicesystem.presentation.desktop.addpanel
 * Author: Lance
 * Date: Jun 27, 2012
 * Editor:
 */
public class AddEditSupplierDialog extends javax.swing.JDialog
{

    private static final long serialVersionUID = 1L;
    private SupplierCrudServiceImpl supplierCrudService;
    private Supplier supplierFromDb;

    public AddEditSupplierDialog(java.awt.Frame parent, boolean modal, HashMap<String, String> values)
    {
        super(parent, modal);
        initComponents();
        supplierCrudService = new SupplierCrudServiceImpl();
        if (!values.isEmpty())
        {
            txtSupName.setText(values.get("SUPPLIER NAME"));
            lblSupNo.setText(values.get("SUPPLIER NUMBER"));
            txtAddress.setText(values.get("ADDRESS"));
            txtContactNo.setText(values.get("CONTACT NUMBER"));
            supplierFromDb = supplierCrudService.findById(Integer.parseInt(values.get("SUPPLIER NUMBER")));
        }

        ValidationComponentUtils.setInputHint(txtSupName, "Please enter the suppliers name");
        ValidationComponentUtils.setInputHint(txtContactNo, "Please enter the suppliers contact number");
        ValidationComponentUtils.setInputHint(txtAddress, "Please enter the suppliers address");

        KeyboardFocusManager.getCurrentKeyboardFocusManager().addPropertyChangeListener(new InfoLableChangeHandler(lblInfo));
    }

    /**
     * This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        txtAddress = new javax.swing.JTextArea();
        jSeparator1 = new javax.swing.JSeparator();
        jLabel7 = new javax.swing.JLabel();
        lblInfo = new javax.swing.JLabel();
        txtSupName = new javax.swing.JTextField();
        lblSupNo = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        txtContactNo = new javax.swing.JTextField();
        jSeparator2 = new javax.swing.JSeparator();
        jLabel6 = new javax.swing.JLabel();
        btnOk = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        lblValidationErrors = new javax.swing.JLabel();
        lblValidationErrors.setVisible(false);
        btnCancel = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        txtAddress.setColumns(20);
        txtAddress.setRows(5);
        jScrollPane1.setViewportView(txtAddress);

        jLabel7.setText("Address");

        lblInfo.setIcon(ValidationResultViewFactory.getInfoIcon());
        lblInfo.setText("Info Lable");

        lblSupNo.setText("New Number is Generated");

        jLabel1.setText("Supplier Number");

        jLabel6.setText("Contact Number");

        btnOk.setText("OK");
        btnOk.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOkActionPerformed(evt);
            }
        });

        jLabel5.setText("Supplier Name");

        lblValidationErrors.setIcon(ValidationResultViewFactory.getCheckIcon());
        lblValidationErrors.setText("Validation Errors");

        btnCancel.setText("Cancel");
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 550, Short.MAX_VALUE)
            .addComponent(jSeparator2, javax.swing.GroupLayout.DEFAULT_SIZE, 550, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(lblSupNo))
                            .addComponent(jLabel5)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel6)
                                    .addComponent(jLabel7))
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addComponent(txtSupName, javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(txtContactNo, javax.swing.GroupLayout.DEFAULT_SIZE, 175, Short.MAX_VALUE)
                                    .addComponent(jScrollPane1))))
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(btnOk, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnCancel)
                                .addContainerGap())
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(lblInfo)
                                .addGap(10, 10, 10))))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lblValidationErrors)
                        .addGap(0, 0, Short.MAX_VALUE))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(lblSupNo))
                .addGap(7, 7, 7)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(txtSupName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel6)
                    .addComponent(txtContactNo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 59, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(btnCancel)
                            .addComponent(btnOk))
                        .addGap(0, 11, 11))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel7)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(lblValidationErrors)
                        .addGap(38, 38, 38)))
                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lblInfo)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnOkActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_btnOkActionPerformed
    {//GEN-HEADEREND:event_btnOkActionPerformed
        String supplierNo = lblSupNo.getText();
        String supplierName = txtSupName.getText();
        String supplierContact = txtContactNo.getText();
        String supplierAddress = txtAddress.getText();
        Supplier supplier = AppFactory.createSupplier(supplierNo, supplierName, supplierContact, supplierAddress);

        SupplierValidator validator = new SupplierValidator(supplierName, supplierContact, supplierAddress);
        ValidationResult validationResult = validator.validate(new ValidationResult());
        ValidationUtil.displayErrorsToLable(validationResult, lblValidationErrors);

        if (validationResult.isEmpty())
        {
            int askUserQuestion = AppUtils.askUserQuestion(this, "Add/Edit the following?\n" + supplier, "Add/Edit", JOptionPane.YES_NO_CANCEL_OPTION);
            if (askUserQuestion == JOptionPane.YES_OPTION)
            {
                try
                {
                    if (supplier.getSupplierNo() == null)
                    {
                        supplierCrudService.create(supplier);
                        AppUtils.showUserMessage(this, "Added the following:\n" + supplier, "Add/Edit", JOptionPane.INFORMATION_MESSAGE);
                    }
                    else
                    {
                        AppFactory.createUpdatedCustomer(supplier, supplierFromDb);
                        supplierCrudService.edit(supplierFromDb);
                        AppUtils.showUserMessage(this, "Updated the following:\n" + supplier, "Add/Edit", JOptionPane.INFORMATION_MESSAGE);
                    }
                    this.dispose();
                }
                catch (PreexistingEntityException ex)
                {
                    OutputError.toLog(ex);
                    OutputError.toUser(ex);
                }
                catch (Exception ex)
                {
                    OutputError.toLog(ex);
                    OutputError.toUser(ex);
                }
            }
        }
    }//GEN-LAST:event_btnOkActionPerformed

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_btnCancelActionPerformed
    {//GEN-HEADEREND:event_btnCancelActionPerformed
        if (AppUtils.askExitConfirm() == JOptionPane.YES_OPTION)
        {
            this.dispose();
        }
    }//GEN-LAST:event_btnCancelActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnOk;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JLabel lblInfo;
    private javax.swing.JLabel lblSupNo;
    private javax.swing.JLabel lblValidationErrors;
    private javax.swing.JTextArea txtAddress;
    private javax.swing.JTextField txtContactNo;
    private javax.swing.JTextField txtSupName;
    // End of variables declaration//GEN-END:variables
}
